Clock


Posted by wayne201299 on 2023-09-22

實作一個小時鐘,DEMO

  1. 設定旋轉的基準點
    transform-origin: 100%;
    
  2. 每秒執行一次
    setInterval(setDate, 1000)
    
  3. 計算時、分、秒的度數,一分&一秒都是6度,一小時則是360/12=30度,為了以12:00:00開始計算,一開始有添加90度,所以所有的度數都要添加90
  4. 每秒更改指針的CSS

       const second = now.getSeconds();
       const secondsDegrees = ((second / 60) * 360) + 90;
       secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
    
       const min = now.getMinutes();
       const minsDegrees = min * 6 + 90
       minHand.style.transform = `rotate(${minsDegrees}deg)`;
    
       const hours = now.getHours();
       const hoursDegrees = hours * 360 / 12 + 90;
       hourHand.style.transform = `rotate(${hoursDegrees}deg)`;
    

知識點

  • 透過CSS transform屬性中的rotate可以旋轉element
  • 透過CSS transform-orgin來設定旋轉的支點

#javascript #css







Related Posts

MTR04_0710

MTR04_0710

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段四:個人專案~Sprint 3)

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段四:個人專案~Sprint 3)

ASP.NET Core  Web API 入門教學 - 資料庫連線設定 Database First,Scaffold-DbContext Build Failed解決方式

ASP.NET Core Web API 入門教學 - 資料庫連線設定 Database First,Scaffold-DbContext Build Failed解決方式


Comments